package com.bill.common.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.bill.common.system.dao.IRuleDAO;
import com.bill.common.system.dto.RuleDTO;
import com.bill.common.system.entity.Rule;
import com.bill.common.user.dto.AccountDTO;
import com.bill.common.user.entity.RegisterUser;
import com.sinba.common.dto.PageDTO;

public class RuleService implements IRuleService {
	public static final Double EVERY_SINGLE_SIZE=1500D;
	@Autowired
	private IRuleDAO ruleDAO;
	public PageDTO findRulePager(RuleDTO qdto,String sord, String sidx){
		PageDTO p = ruleDAO.findRulePager(qdto, sord, sidx);
		
		List<Rule> ruleList = (List<Rule>)p.getData();
		
		List<RuleDTO> dtos = new ArrayList<RuleDTO>();
		
		for(Rule entity:ruleList){
			RuleDTO dto = new RuleDTO();
			dto.entity2dto(entity, dto);
			dtos.add(dto);
		}
		p.setData(dtos);
		
		return p;
	};
	@Transactional
	public void saveRule(RuleDTO dto){
		Rule rule = new Rule();
		dto.dto2entity(dto, rule);
		ruleDAO.save(rule);
	};
	@Transactional
	public void editRule(RuleDTO dto){
		Rule rule = ruleDAO.findById(dto.getRuleId());
		dto.dto2entity(dto, rule);
		ruleDAO.merge(rule);
	};
	@Transactional
	public void deleteRule(Long[] ids){
		ruleDAO.deleteByIds(ids);
	};
	@Transactional
	public RuleDTO findRuleByRuleCode(RuleDTO dto){
		Rule rule = ruleDAO.findUniqueBy("ruleCode",dto.getRuleCode());
		RuleDTO ruleDTO = new RuleDTO();
		ruleDTO.entity2dto(rule, ruleDTO);
		return ruleDTO;
	};
	@Transactional
	public Map<String, Double> findRuleMap(String[] ruleCode){
		
		Map<String, Double> map = new HashMap<String, Double>();
		List<Rule> rules = ruleDAO.findRuleByCode(ruleCode);
		for(Rule rule:rules){
			map.put(rule.getRuleCode(), rule.getRuleValue());
		}
		return map;
	}
	
	
	/**
	 * 查询规则DTO详细
	 * @return RuleDTO
	 */
	@Transactional
	public RuleDTO findRuleInfo(){
		RuleDTO dto = new RuleDTO();
		List<Rule> rules = ruleDAO.findAll();
		if(rules!=null && rules.size()>0){
			RuleDTO.entity2dto(rules.get(0), dto);
		}else{
			Rule rule = new Rule();
			rule.setRuleName("defult");
			ruleDAO.save(rule);
			RuleDTO.entity2dto(rule, dto);
		}
		return dto;
	};
	
}
